package root.electronclass.electronclass.home.widget

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs

class EnhancedScaleLayoutManager @JvmOverloads constructor(
    context: Context,
    orientation: Int = RecyclerView.HORIZONTAL,
    reverseLayout: Boolean = false
) : LinearLayoutManager(context, orientation, reverseLayout) {

    private val shrinkAmount = 0.35f
    private val shrinkDistance = 0.9f
    private val maxTranslateX = 306f - 182f

    override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
        val scrolled = super.scrollHorizontallyBy(dx, recycler, state)
        if (orientation == HORIZONTAL) {
            updateScale()
        }
        return scrolled
    }

    override fun onLayoutCompleted(state: RecyclerView.State?) {
        super.onLayoutCompleted(state)
        updateScale()
    }

    private fun updateScale() {
        val parentCenter = width / 2f

        for (i in 0 until childCount) {
            val child = getChildAt(i) ?: continue
            val childCenter = (child.left + child.right) / 2f
            val x = parentCenter - childCenter
            val distanceFromCenter = abs(x)

            // 计算缩放比例
            val scale = 1f - shrinkAmount *
                    (distanceFromCenter / (parentCenter * shrinkDistance)).coerceAtMost(1f)

            child.scaleX = scale
            child.scaleY = scale
            child.translationX = (1 - scale) * maxTranslateX * if (x > 0) 1f else -1f

            // 透明度效果
            child.alpha = 0.5f + 0.5f * scale
        }
    }
}